<template>
  <div class="code-canvas">
    <canvas ref="codecanvas"></canvas>
  </div>
</template>
<script lang="ts" setup>
const codecanvas = ref<HTMLCanvasElement | null>(null);
const setCanvas = () => {
  const width = document.documentElement.clientWidth + devicePixelRatio;
  const height = document.documentElement.clientHeight + devicePixelRatio;
  if (!codecanvas.value) return;
  codecanvas.value.width = width;
  codecanvas.value.height = height;
  const ctx = codecanvas.value.getContext("2d") as CanvasRenderingContext2D;
  const fontSize = 12 * devicePixelRatio;
  const columnWidth = fontSize;
  const columnNum = Math.floor(width / columnWidth);
  const nextChars = new Array(columnNum).fill(0);
  function draw() {
    ctx.fillStyle = "rgba(0, 0, 0, 0.1)";
    ctx.fillRect(0, 0, width, height);
    for (let i = 0; i < columnNum; i++) {
      const char = getRandomChar();
      ctx.fillStyle = getRandomColor();
      ctx.font = `${fontSize}px Arial`;
      const x = i * columnWidth;
      const index = nextChars[i];
      const y = (index + 1) * fontSize;
      ctx.fillText(char, x, y);
      nextChars[i]++;
      if (y > height && Math.random() > 0.99) {
        nextChars[i] = 0;
      } else {
        nextChars[i]++;
      }
    }
  }
  setInterval(draw, 50);
};

/** 获取随机颜色 */
const getRandomColor = (): string => {
  const letters = "0123456789ABCDEF";
  let color = "#";
  for (let i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
};
/** 获取随机字符 */
const getRandomChar = (): string => {
  const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  return chars[Math.floor(Math.random() * chars.length)];
};
onMounted(() => {
  setCanvas();
});
</script>
<style lang="scss" scoped>
.code-canvas {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  z-index: -1;
  overflow: hidden;
}
</style>